<template>
  <div class="play-progress">
    <div class="progress" ref="progress"
         @mousemove="handleMouseMove"
         @mousedown="handleMouseDown">
      <div class="line" :style="{width: `${pct * 100}%`}">
      </div>
    </div>
    <div class="time-box">{{ formatTime(current) }}/{{ formatTime(duration) }}</div>
  </div>
</template>

<script setup lang="ts">
import {ref, watch, watchEffect} from "vue";
import {formatTime} from "../common/utils";
import {current, duration} from "../uses/usePlayer";

const props = defineProps({
  duration: {
    type: Number,
    default: 0
  },
  current: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits<{
  (e: 'change', value: number): void
}>();
let isMove = false;
const progress = ref();
const pct = ref(0);
watch([current, duration], () => {
  pct.value = current.value / duration.value;
});

const handleMouseDown = (e: MouseEvent) => {
  isMove = true;
  pct.value = e.offsetX / progress.value.clientWidth;
  emit('change', pct.value * props.duration);
};
const handleMouseUp = (e: MouseEvent) => {
  isMove = false;
};
const handleMouseMove = (e: MouseEvent) => {
  if (isMove) {
    const offsetX = Math.min(Math.max(0, e.pageX - progress.value.getBoundingClientRect().left), progress.value.clientWidth);
    pct.value = offsetX / progress.value.clientWidth;
    emit('change', pct.value * props.duration);
  }
};

watchEffect((onInvalidate) => {
  window.addEventListener('mouseup', handleMouseUp);
  window.addEventListener('mousemove', handleMouseMove);
  onInvalidate(() => {
    window.removeEventListener('mouseup', handleMouseUp);
    window.removeEventListener('mousemove', handleMouseMove);
  });
})
</script>

<style scoped lang="scss">
.play-progress {
  display: flex;
  flex: 1;
  align-items: center;

  .progress {
    flex: 1;
    height: 5px;
    background: rgba(0, 0, 0, 0.1);
    margin: 0 10px;
    border-radius: 3px;
    overflow: hidden;
    cursor: pointer;

    .line {
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
    }
  }

  .time-box {
    font-size: 12px;
  }
}
</style>
